package org.jeecg.modules.app.pay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.app.pay.service.PayService;
import org.jeecg.modules.app.util.AliPayConfig;
import org.jeecg.modules.power.order.entity.YlMemberOrder;
import org.jeecg.modules.power.order.service.IYlMemberOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @BelongsProject: jeecg-boot-parent
 * @BelongsPackage: org.jeecg.modules.app.pay.controller
 * @Author: mi
 * @CreateTime: 2024-07-13 16:11
 * @Description:
 */
@CrossOrigin
@Api(tags = "统一回调")
@RestController
@RequestMapping("/api/pay")
public class CallbackUrlController {


    @Autowired
    private IYlMemberOrderService ylMemberOrderService;//会员订单表



    @Autowired
    private PayService payService;//回调业务层


    @ApiOperation("模拟订单回调")
    @ApiImplicitParam(name = "payNumber" ,value = "支付单号",required = true)
    @PostMapping("/textOrder")
    public Result<?> textOrder(String payNumber){
        //充值订单
        return Result.OK();
    }








    /**
     * 支付宝统一回调
     * @param request
     * @param response
     * @throws AlipayApiException
     * @throws IOException
     */
    @PostMapping(value = "/AliPayNotify")
    public void AliPayNotify(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, IOException {

        response.setContentType("text/html;charset=utf-8");
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == (values.length - 1)) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            params.put(name, valueStr);
        }
        boolean signVerified =  AlipaySignature.rsaCheckV1(params, AliPayConfig.alipay_public_key,AliPayConfig.charset,AliPayConfig.sign_type);
        if (!signVerified){
            System.out.println("验签失败|||");
            response.getWriter().write("fail");
        }
        // 商户订单号
        String mainOrderNo = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
        // 交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
        //付款金额
        String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

        System.out.println("-----------支付宝进入------------------"+mainOrderNo+"----------金额"+total_amount+"元");




        if (trade_status.equals("TRADE_SUCCESS")){
            if (mainOrderNo.substring(0,2).equals("CZ")){
                //会员充值订单
                YlMemberOrder ylMemberOrder=    ylMemberOrderService.getOne(new LambdaQueryWrapper<YlMemberOrder>().eq(YlMemberOrder::getPayStatus,0).eq(YlMemberOrder::getPayNumber,mainOrderNo));
                if (oConvertUtils.isNotEmpty(ylMemberOrder)){
                    //处理订单方法
                    ylMemberOrder.setPayMethod(2);//支付方式1、微信支付 2、支付宝支付
                    ylMemberOrder.setPayTime(new Date());//支付时间
                    ylMemberOrder.setPayStatus(1);//支付状态（0未支付，1已支付
                    payService.callbackMemberOrder(ylMemberOrder);
                }
            }


        }




        response.getWriter().write("success");




    }











}
